<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}用户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="userInfo"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="用户头像" prop="avatar">
        <UploadImg v-model:image-url="userInfo.userAvatar" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="头像选择">
        <el-button @click="changeAvatar" type="primary">随机头像</el-button>
      </el-form-item>
      <p></p>
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="userInfo.username" placeholder="请填写用户账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="userInfo.name" placeholder="请填写用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="userGender">
        <el-select v-model="userInfo.userGender" placeholder="请选择性别" clearable>
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="userIdentity">
        <el-input v-model="userInfo.userIdentity" placeholder="请填写身份证号" clearable></el-input>
      </el-form-item>
      <el-form-item label="电话号" prop="userPhone">
        <el-input v-model="userInfo.userPhone" placeholder="请填写电话号" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户身份" prop="userRole">
        <el-select v-model="userInfo.userRole" placeholder="请选择用户身份" clearable>
          <el-option v-for="item in userRole" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门编号" prop="departmentId" v-show="showDepartment">
        <el-input v-model="userInfo.departmentId" placeholder="请选择部门" readonly></el-input>
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName" v-show="showDepartment">
        <el-input v-model="userInfo.departmentName" placeholder="请选择部门" readonly></el-input>
      </el-form-item>
      <el-button type="primary" v-show="showDepartment" @click="openDepartmentDialog">选择部门</el-button>
      <el-button v-show="showDepartment" @click="clearDepartment">清空部门</el-button>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button @click="newUser">随机生成</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
  <SubstationDialog ref="substationRef" @get-substation="getSubstation" />
  <WarehouseDialog ref="warehouseRef" @get-warehouse="getWarehouse" />
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, watch, computed } from "vue";
import { genderType, userRole } from "@/utils/serviceDict";
import { ElMessage, FormInstance } from "element-plus";
import { User, Warehouse } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
import SubstationDialog from "./SubstationDialog.vue";
import WarehouseDialog from "./WarehouseDialog.vue";
import { Substation } from "@/api/interface";
import { imageLinks } from "@/utils/avatarLinks";

interface DrawerProps {
  title: string;
  isView: boolean;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: ""
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

const userInfo = ref<Partial<User.UserEntity>>({});
//随机选取一个头像
userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];

const rules = reactive({
  name: [
    { required: true, message: "请填写用户姓名" },
    { pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: "姓名格式不正确" }
  ],
  userGender: [{ required: true, message: "请选择性别" }],
  username: [
    { required: true, message: "请填写用户账号" },
    { min: 4, max: 20, message: "账号长度为4到20个字符" }
  ],
  userIdentity: [
    { required: true, message: "请填写身份证号" },
    { pattern: /^\d{17}[\dXx]$/, message: "身份证号格式不正确" }
  ],
  userRole: [{ required: true, message: "请选择用户身份" }],
  userPhone: [
    { required: true, message: "请填写电话号" },
    { pattern: /^1[3-9]\d{9}$/, message: "电话号格式不正确" }
  ],
  departmentId: [{ required: true, message: "请选择部门" }],
  departmentName: [{ required: true, message: "请选择部门" }]
});

const showDepartment = computed(() => {
  if (
    userInfo.value.userRole === 3 ||
    userInfo.value.userRole === 4 ||
    userInfo.value.userRole === 5 ||
    userInfo.value.userRole === 8
  ) {
    return true;
  } else {
    return false;
  }
});

// 监听userRole的变化
watch(
  () => userInfo.value.userRole,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      userInfo.value.departmentId = undefined; // 清空departmentId
      userInfo.value.departmentName = undefined; // 清空departmentName
    }
  }
);
const substationRef = ref<InstanceType<typeof SubstationDialog> | null>(null);
const warehouseRef = ref<InstanceType<typeof WarehouseDialog> | null>(null);
const openDepartmentDialog = () => {
  if (userInfo.value.userRole == 5 || userInfo.value.userRole == 8) {
    //分站dialog
    substationRef.value?.open();
  } else if (userInfo.value.userRole == 3) {
    //中心库房dialog
    warehouseRef.value?.open(0);
  } else if (userInfo.value.userRole == 4) {
    //分站库房dialog
    warehouseRef.value?.open(1);
  }
};
const clearDepartment = () => {
  userInfo.value.departmentId = undefined; // 清空departmentId
  userInfo.value.departmentName = undefined; // 清空departmentName
};

const findLabelByValue = (value: number | any) => {
  const role = userRole.find(role => role.value === value);
  return role ? role.label : undefined;
};

const changeAvatar = () => {
  //随机选取一个头像
  userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!showDepartment.value) {
      // 非分站和库房的用户，部门id等于role,部门名称等于标签值
      userInfo.value.departmentId = userInfo.value.userRole;
      userInfo.value.departmentName = findLabelByValue(userInfo.value.userRole);
    }
    if (!valid) return;

    // if (userInfo.value.departmentId == undefined || userInfo.value.departmentName == undefined) {
    //   ElMessage.error({ message: `请选择部门！` });
    //   return;
    // }
    try {
      await drawerProps.value.api!(userInfo.value);
      ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

//获取子组件传来的分站信息
const getSubstation = (row: Substation.ResSubstationList) => {
  userInfo.value.departmentId = row.substationId;
  userInfo.value.departmentName = row.substationName;
};

//获取子组件传来的库房信息
const getWarehouse = (row: Warehouse.ResWarehouseList) => {
  userInfo.value.departmentId = row.warehouseId;
  userInfo.value.departmentName = row.warehouseName;
};

const newUser = () => {
  //随机选取一个头像
  userInfo.value.userAvatar = imageLinks[Math.floor(Math.random() * imageLinks.length)];
  userInfo.value.username = "12341165";
  userInfo.value.name = "力咖啡";
  userInfo.value.userGender = 1;
  userInfo.value.userIdentity = "140109200207054517";
  userInfo.value.userPhone = "15333008409";
};
defineExpose({
  acceptParams
});
</script>
